package com.cxh.controller.sys;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.cxh.base.BaseController;
import com.cxh.entity.SysRole;
import com.cxh.entity.SysUser;
import com.cxh.util.CommonUtility;
import com.cxh.util.DateUtility;
import com.cxh.util.json.JSONUtil;

import net.sf.json.JsonConfig;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 类说明：
 * @author  ChenXH
 * @date  2018-11-29 11:14:13
 */
@Controller
@RequestMapping(value = "/controller/sysUser")
public class SysUserController extends BaseController {

    /**
     * 方法说明：进入页面
     * @author  ChenXH
     * @date  2018-11-29 11:14:13
     */
    @RequestMapping(value = "/list")
    public ModelAndView list (HttpServletRequest request, HttpServletResponse response){
        ModelAndView model =  new ModelAndView();
        model.setViewName("sys/sysUser/sysUserList");
        return model;
    }

    /**
     * 方法说明：获得表格数据
     * @author  ChenXH
     * @date  2018-11-29 11:14:13
     */
    @RequestMapping(value = "/showList")
    @ResponseBody
    public String showList (HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String, Object> params){
        String json="";
        //获得  页码数
        Integer page=CommonUtility.isEmpty(params.get("page"))?1:Integer.parseInt(params.get("page")+"");
        //获得 每页的行数
        Integer limit=CommonUtility.isEmpty(params.get("limit"))?10:Integer.parseInt(params.get("limit")+"");
        //设置 分页参数
        PageHelper.startPage(page,limit);
        //调用 查询方法
        List<SysUser> sysUserList=sysUserService.loadPageList(params);
        //将角色分开标签
        for (SysUser sysUser : sysUserList) {
        	String roleName = sysUser.getRoleName();
        	if(roleName.indexOf(";") != -1){
        		String[] roleNames = roleName.split(";");
        		String rolenameSpan = "";
        		for (String rolename : roleNames) {
        			rolenameSpan += "<span style='color: #009688;padding:5px;'>"+rolename+"</span>";
				}
        		sysUser.setRoleName(rolenameSpan);
        	}else{
        		String rolenameSpan = "<span style='color: #009688;padding:5px'>"+roleName+"</span>";
    			sysUser.setRoleName(rolenameSpan);
        	}
        	
		}
        //处理数据
        PageInfo<SysUser> pageInfo=new PageInfo<SysUser>(sysUserList);
        try {
            //转换 时间格式/并将数据转换成json字符串
            JsonConfig jsonConfig = JSONUtil.getJsonConfig(DateUtility.DateFormat1);
            json= JSONUtil.toLayUIJSONAll(pageInfo.getTotal(),pageInfo.getList(), jsonConfig);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }


    /**
     * 方法说明：进入编辑页面
     * @author  ChenXH
     * @date  2018-11-29 11:14:13
     */
    @RequestMapping(value = "/edit")
    public ModelAndView edit (HttpServletRequest request, HttpServletResponse response){
        //获得要修改数据的Id
        int entityId=CommonUtility.isEmpty(request.getParameter("entityId"))?0:Integer.parseInt(request.getParameter("entityId"));
        ModelAndView model=new ModelAndView();
        SysUser sysUser=new SysUser();
        
        ArrayList<Object> mapList = new ArrayList<Object>();
       //查询所有的角色
        List<SysRole> sysRoleList = sysRoleService.selectAll();
        for (SysRole sysRole : sysRoleList) {
        	HashMap<String, Object> hashMap = new HashMap<String,Object>();
        	hashMap.put("id", sysRole.getId().toString());
        	hashMap.put("name", sysRole.getRolename());
        	mapList.add(hashMap);
		}
        Gson gson = new Gson();
        String allRoles = gson.toJson(mapList);
        model.addObject("allRoles",allRoles);
        List<Integer> roleIds = new ArrayList<Integer>();
        try {
            //判断是 修改  还是 新增
            if (!CommonUtility.isEmpty(entityId)&&entityId>0) {
                sysUser = sysUserService.selectByPrimaryKey(entityId);
                //查询用户拥有的角色
                 roleIds = sysUserRoleService.getRoleByUserId(sysUser.getUserid());
                // 进行数据准备
                model.addObject("sysUser",sysUser);
            }
            
            model.addObject("roleIds",gson.toJson(roleIds));
            //返回视图位置
            model.setViewName("sys/sysUser/sysUserForm");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return model;
    }

    /**
     * 方法说明：保存/修改
     * @author  ChenXH
     * @date  2018-11-29 11:14:13
     */
    @RequestMapping(value = "/save")
    @ResponseBody
    public String save (HttpServletRequest request, HttpServletResponse response,@RequestParam  Map<String,Object> jsonMap){
        //执行状态（0成功；1失败）
        int flag=0;
        int entityId=CommonUtility.isEmpty(jsonMap.get("entityId"))?0:Integer.parseInt(jsonMap.get("entityId")+"");
        //{username=测试账号, entityId=, userid=cxh, roleids=1,2}
        //进行 修改
        if(entityId>0){
            SysUser sysUser=sysUserService.selectByPrimaryKey(entityId);
            if(!CommonUtility.isEmpty(sysUser)){

                try {
                	sysUser.setUsername(jsonMap.get("username").toString());
                	sysUser.setUserid(jsonMap.get("userid").toString());
                	//更新用户信息，以及用户对应的角色
                	sysUserService.updateSysUser(sysUser,jsonMap);
                    //operationLog(request, "修改用户" + user.getLoginName(), TableConstants.LOG_TYPES_EDIT);
                }catch (Exception e) {
                    flag = 1;
                    e.printStackTrace();
                }
            }else{
                flag=1;
            }
        }else{
            try {
            	//先查询该用户的登录名是否存在
            	SysUser sysUser= sysUserService.getUserByUserId(jsonMap.get("userid").toString());
            	//用户已存在，请换一个用户名
            	if(sysUser != null){
            		return "2";
            	}
                //新增
                sysUserService.addSysUser(jsonMap);
                //operationLog(request, "添加用户" + user.getLoginName(), TableConstants.LOG_TYPES_ADD);
            }catch (Exception e) {
                flag = 1;
                e.printStackTrace();
            }
        }

        return flag+"";
    }

    /**
     * 方法说明：删除
     * @author  ChenXH
     * @date  2018-11-29 11:14:13
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public String delete (HttpServletRequest request, HttpServletResponse response){
        int entityId=CommonUtility.isEmpty(request.getParameter("entityId"))?0:Integer.parseInt(request.getParameter("entityId"));
        //执行状态（0成功；1失败）
        int flag = 0;
        if(entityId>0){
            SysUser sysUser = sysUserService.selectByPrimaryKey(entityId);
            if(!CommonUtility.isEmpty(sysUser)){
                //sysUser.setIsDel(0);
                try {
                    //sysUserService.updateByPrimaryKey(sysUser);
                    sysUserService.delete(sysUser);
                    //operationLog(request, "删除用户" + user.getLoginName(), TableConstants.LOG_TYPES_DEL);
                }catch (Exception e) {
                    flag = 1;
                    e.printStackTrace();
                }
            }
        }
        return flag+"";
    }


    /**
     * @类功能说明：更改密码页面
     * @作者：Chenxh
     * @创建时间：2019年1月2日上午9:03:12
     */
    @RequestMapping("/changePassword")
    public String changePassword(HttpServletRequest request){
    	return "sys/sysUser/changePwdForm";
    }
    
    /**
     * @类功能说明：更新密码
     * @作者：Chenxh
     * @创建时间：2019年1月2日上午9:48:09
     */
    @RequestMapping("/updatePwd")
    @ResponseBody
    public String updatePwd(HttpSession session,String passwordOrd,String passwordNew){
    	SysUser sysUser= (SysUser)session.getAttribute("user");
    	//旧密码对比
    	if(sysUser.getPassword().equals(passwordOrd)){
    		SysUser user = sysUserService.selectByPrimaryKey(sysUser.getId());
    		user.setPassword(passwordNew);
    		sysUserService.updateByPrimaryKey(user);
    	}else{
    		//旧密码不正确
    		return "2";
    	}
    	return "0";
    }
}
